package com.cts.tmall.com.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;

/**
 * Spring 工具类
 *
 * @author leibing.song
 * @since 2020-07-16
 */
@Slf4j
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return SpringUtils.applicationContext;
    }

    public static Object getBean(String beanName) {
        if (StringUtils.isBlank(beanName)) {
            throw new NoSuchBeanDefinitionException(beanName);
        }
        return getApplicationContext().getBean(beanName);
    }

    public static <T> T getBean(Class<T> beanType) {
        if (beanType == null) {
            throw new NoSuchBeanDefinitionException(beanType.getSimpleName());
        }
        return getApplicationContext().getBean(beanType);
    }

    public static <T> Collection<T> getBeansOfType(Class<T> beanType) {
        return beanType == null || getApplicationContext().getBeansOfType(beanType).isEmpty() ? Collections.emptyList()
                : getApplicationContext().getBeansOfType(beanType).values();
    }
}
